package edu.zueb.sport.rest;

import com.google.common.collect.Lists;
import edu.zueb.sport.entity.User;
import edu.zueb.sport.enums.MenuEnum;
import edu.zueb.sport.enums.UserTypeEnum;
import edu.zueb.sport.rest.api.Menu;
import edu.zueb.sport.rest.api.RestResponse;
import edu.zueb.sport.utils.JsonUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "菜单管理", description = "菜单管理")
@Slf4j
@RestController
@RequestMapping(MenuRestController.PATH_MENU)
public class MenuRestController {

    public static final String PATH_MENU = "/api/role";

    @PostMapping(value = "/list")
    public RestResponse<List<Menu>> list(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        User user = AuthRestController.TOKEN_CACHE.getIfPresent(token);
        if (user == null) {
            return RestResponse.fail("用户未登录");
        }
        log.info("user={}", JsonUtils.toJson(user));
        Integer userType = user.getUserType();
        UserTypeEnum userTypeEnum = UserTypeEnum.toUserTypeEnum(userType);
        if (userTypeEnum == null) {
            return RestResponse.fail("用户类型错误");
        }
        List<MenuEnum> menuEnums = MenuEnum.listByUserTypeEnum(userTypeEnum);
        log.info("用户类型={}|菜单列表={}", userTypeEnum, menuEnums);
        // 根据菜单 id 对菜单进行排序
        menuEnums.sort(Comparator.comparing(MenuEnum::getMenuId));

        // 使用深度优先遍历构建菜单树
        Map<String, List<MenuEnum>> menuMap = new HashMap<>();
        for (MenuEnum menuEnum : menuEnums) {
            String parentId = menuEnum.getParentId();
            menuMap.computeIfAbsent(parentId, k -> Lists.newArrayList()).add(menuEnum);
        }
        // 从根节点开始构建菜单树
        List<Menu> menus = buildMenuTree("0", menuMap);
        return RestResponse.success(menus);
    }

    private List<Menu> buildMenuTree(String parentId, Map<String, List<MenuEnum>> menuMap) {
        List<MenuEnum> menuEnums = menuMap.getOrDefault(parentId, Lists.newArrayList());
        List<Menu> menus = Lists.newArrayList();
        for (MenuEnum menuEnum : menuEnums) {
            Menu menu = toMenu(menuEnum);
            // 递归构建子菜单
            List<Menu> children = buildMenuTree(menuEnum.getMenuId(), menuMap);
            if (CollectionUtils.isEmpty(children)) {
                children = null;
            }
            menu.setChildren(children);
            menus.add(menu);
        }
        return menus;
    }

    private static Menu toMenu(MenuEnum menuEnum) {
        Menu menu = new Menu();
        menu.setPath(menuEnum.getPath());
        menu.setComponent(menuEnum.getComponent());
        menu.setRedirect(menuEnum.getRedirect());
        menu.setName(menuEnum.getName());
        menu.setMeta(menuEnum.getMeta());
        return menu;
    }
}
